package com.ruoyi.web.interceptor;

import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.JWTUtil;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author czg
 * @date 2021/9/19 6:12 下午
 */
@Configuration
    public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从 http 请求头中取出 token
        String token = request.getHeader("token");
        if ("no_login".equals(token)) {
            return true;
        }
        if (StringUtils.isEmpty(token)) {
            throw new GlobalException("token invalid");
        }
        if (JWTUtil.decodeToken(token) != null) {
            String userId = JWTUtil.decodeToken(token);
            redisTemplate.opsForValue().set(token, userId);
            return true;

        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        redisTemplate.delete(request.getHeader("token"));
    }
}
